package com.token.sysflow.core;

import com.token.sql.IntegrateSql;
import com.token.sysflow.enumerate.ApprovalTypeEnum;
import com.token.sysflow.exception.ErrorCodeEnum;
import com.token.sysflow.exception.FlowException;
import com.token.sysflow.hander.ApproveProcess;
import com.token.sysflow.impl.AbstractFlowHandlerImpl;
import com.token.sysflow.impl.SubmitFlowImpl;

/**
 * @author chenjianxiong 2020/4/13
 */
public class ReturnFlow extends SubmitFlow {
    public ReturnFlow(IntegrateSql f, String keyUnid) throws Exception {
        super(f, keyUnid);
    }


    @Override
    public void execute(AbstractFlowHandlerImpl flowHandler) throws Exception {
        submitFlow = (SubmitFlowImpl) flowHandler;

        //检查流程状态，结束和终止不允许操作
        checkFlowStatus();

        //初始化起草人、申请人、当前人。
        initUserInfo(approveProcess.getCreater(),approveProcess.getApplyer(),submitFlow.getActionUser());

        //组织会审和组织会签不允许退回操作。
        if((approveProcess.getApprovalType() == ApprovalTypeEnum.ZZHQ.getId()) || (approveProcess.getApprovalType() == ApprovalTypeEnum.ZZHS.getId())){
            throw new FlowException(ErrorCodeEnum.FLOWRETURN_ZZHS_ZZHQ);
        }

        //判断当前用户是否是当前办理人
        if (!approveProcess.isStepApproves(flowHandler.getActionUser(), ApproveProcess.STATUS_IND)) {
            throw new FlowException(ErrorCodeEnum.CHECK_APPROVE,flowHandler.getActionUser());
        }

        //判断目标环节是否相同
        if(fromStep.getStepId().equals(submitFlow.getStepId())){
            throw new FlowException(ErrorCodeEnum.FLOWRETURN_STEP_SAME);
        }

        //退回标识
        approveProcess.setReturnAction(true);

        //设置目标流程
        super.setToFlowById(submitFlow.getFlowId());

        //设置目标环节
        super.setToStepById(submitFlow.getStepId());

        //检查目标环节是否能退回
        if(!getToStep().isCanReturn()){
            throw new FlowException(ErrorCodeEnum.CONFIG_RETURN);
        }

        //删除当前的办理人
        approveProcess.delStepAllApproves(fromStep);

        //根据环节类型来退回。
        super.returnByToStepType();

        //生成新的流转记录和办理意见
        super.createFlowApproveLog(flowHandler);

        //处理知会
        this.handleSystemNotify("流程退回","单据【"+ approveProcess.getFlowNo() +"】有用户操作了“退回”，原因是："+ submitFlow.getOpinions() +"。",flowRecord.getFlowRecordApprovers());
    }

}
